package com.xuecheng.learning.service.impl;

import com.alibaba.fastjson.JSON;
import com.xuecheng.base.model.RestResponse;
import com.xuecheng.content.model.po.CoursePublish;
import com.xuecheng.content.model.po.Teachplan;
import com.xuecheng.learning.feignclient.ContentServiceClient;
import com.xuecheng.learning.feignclient.MediaServiceClient;
import com.xuecheng.learning.model.dto.XcCourseTablesDto;
import com.xuecheng.learning.service.LearningService;
import com.xuecheng.learning.service.MyCourseTablesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
@Slf4j
public class LearningServiceImpl implements LearningService {

    @Autowired
    MyCourseTablesService myCourseTablesService ;


    @Autowired
    ContentServiceClient contentServiceClient ;

    @Autowired
    MediaServiceClient mediaServiceClient ;


    @Override
    public RestResponse<String> getVideo(String userId, Long courseId, Long teachplanId, String mediaId) {
        //        查询课程信息
        CoursePublish coursepublish = contentServiceClient.getCoursepublish(courseId);
        if(StringUtils.isEmpty(coursepublish)){
            return RestResponse.validfail("课程不存在");
        }
        //判断是否可以试学
//        String teachplanStr = coursepublish.getTeachplan();
//        List<Teachplan> teachplan = JSON.parseObject(teachplanStr, List.class);
//        String isPreview = teachplan.getIsPreview();
        Teachplan teachplan = contentServiceClient.getTeachplan(teachplanId);
        if("1".equals(teachplan.getIsPreview())){
            //有资格学习，返回视频播放地址
            return mediaServiceClient.getPlayUrlByMediaId(mediaId);
        }
        //        获取学习资格
//        远程调用媒资服务获取视频地址
        if(!StringUtils.isEmpty(userId)){
            XcCourseTablesDto learningStatus = myCourseTablesService.getLearningStatus(userId, courseId);
            String learnStatus = learningStatus.getLearnStatus();
            if("702002".equals(learnStatus)){
                return RestResponse.validfail("无法学习，因为没有选课或选课后没有支付");
            }else if("702003".equals(learnStatus)){
                return RestResponse.validfail("已过期需要重新支付");
            }else {
                //有资格学习，返回视频播放地址
                return mediaServiceClient.getPlayUrlByMediaId(mediaId);
            }
        }

//        取出收费规则
        String charge = coursepublish.getCharge();
        if("201000".equals(charge)){
//            有资格学习
            return mediaServiceClient.getPlayUrlByMediaId(mediaId);
        }



        return RestResponse.validfail("该课程没有选课");
    }
}
